/**
 * MessageBroker 工厂 - 用于创建真实或模拟的实现
 */

import { MessageBroker, MessageProcessor, ToolExecutor, MemoryOperator } from '../message-broker';

// 模拟实现（仅在测试环境中导入）
let MockMessageProcessor: any;
let MockToolExecutor: any;
let MockMemoryOperator: any;

// 动态导入模拟实现（避免在生产环境中包含测试代码）
async function loadMockImplementations() {
  if (process.env.NODE_ENV === 'test' || process.env.ENABLE_MOCKS === 'true') {
    const mockModule = await import('../__tests__/mocks/message-processor.mock');
    MockMessageProcessor = mockModule.MockMessageProcessor;
    
    const toolMockModule = await import('../__tests__/mocks/tool-executor.mock');
    MockToolExecutor = toolMockModule.MockToolExecutor;
    
    const memoryMockModule = await import('../__tests__/mocks/memory-operator.mock');
    MockMemoryOperator = memoryMockModule.MockMemoryOperator;
  }
}

export interface MessageBrokerConfig {
  mode: 'production' | 'development' | 'test';
  messageProcessor?: MessageProcessor;
  toolExecutor?: ToolExecutor;
  memoryOperator?: MemoryOperator;
  mockOptions?: {
    responseDelay?: number;
    chunkDelay?: number;
    executionDelay?: number;
    operationDelay?: number;
    shouldFail?: boolean;
    failureRate?: number;
  };
}

export class MessageBrokerFactory {
  private static instance: MessageBrokerFactory;

  private constructor() {}

  static getInstance(): MessageBrokerFactory {
    if (!MessageBrokerFactory.instance) {
      MessageBrokerFactory.instance = new MessageBrokerFactory();
    }
    return MessageBrokerFactory.instance;
  }

  /**
   * 创建 MessageBroker 实例
   */
  async createMessageBroker(config: MessageBrokerConfig): Promise<MessageBroker> {
    const {
      mode,
      messageProcessor,
      toolExecutor,
      memoryOperator,
      mockOptions = {}
    } = config;

    // 如果提供了具体的实现，直接使用
    if (messageProcessor && toolExecutor && memoryOperator) {
      return new MessageBroker(messageProcessor, toolExecutor, memoryOperator);
    }

    // 根据模式决定使用真实实现还是模拟实现
    switch (mode) {
      case 'production':
        return this.createProductionMessageBroker(config);
      
      case 'development':
        return this.createDevelopmentMessageBroker(config);
      
      case 'test':
        return this.createTestMessageBroker(config);
      
      default:
        throw new Error(`Unknown mode: ${mode}`);
    }
  }

  /**
   * 创建生产环境的 MessageBroker
   */
  private async createProductionMessageBroker(config: MessageBrokerConfig): Promise<MessageBroker> {
    // 在生产环境中，这里应该创建真实的实现
    // 例如：连接到真实的 AI API、数据库等
    
    // 暂时抛出错误，提醒需要实现真实的处理器
    throw new Error('Production implementations not yet available. Please provide concrete implementations.');
  }

  /**
   * 创建开发环境的 MessageBroker
   */
  private async createDevelopmentMessageBroker(config: MessageBrokerConfig): Promise<MessageBroker> {
    // 开发环境可以使用模拟实现来快速开发和调试
    await loadMockImplementations();
    
    if (!MockMessageProcessor || !MockToolExecutor || !MockMemoryOperator) {
      throw new Error('Mock implementations not available');
    }

    const { mockOptions = {} } = config;

    const messageProcessor = new MockMessageProcessor({
      responseDelay: mockOptions.responseDelay,
      chunkDelay: mockOptions.chunkDelay,
      shouldFail: mockOptions.shouldFail
    });

    const toolExecutor = new MockToolExecutor({
      executionDelay: mockOptions.executionDelay,
      shouldFail: mockOptions.shouldFail,
      failureRate: mockOptions.failureRate
    });

    const memoryOperator = new MockMemoryOperator({
      operationDelay: mockOptions.operationDelay,
      shouldFail: mockOptions.shouldFail
    });

    return new MessageBroker(messageProcessor, toolExecutor, memoryOperator);
  }

  /**
   * 创建测试环境的 MessageBroker
   */
  private async createTestMessageBroker(config: MessageBrokerConfig): Promise<MessageBroker> {
    await loadMockImplementations();
    
    if (!MockMessageProcessor || !MockToolExecutor || !MockMemoryOperator) {
      throw new Error('Mock implementations not available');
    }

    const { mockOptions = {} } = config;

    // 测试环境使用更快的响应时间
    const messageProcessor = new MockMessageProcessor({
      responseDelay: mockOptions.responseDelay ?? 10,
      chunkDelay: mockOptions.chunkDelay ?? 5,
      shouldFail: mockOptions.shouldFail ?? false
    });

    const toolExecutor = new MockToolExecutor({
      executionDelay: mockOptions.executionDelay ?? 10,
      shouldFail: mockOptions.shouldFail ?? false,
      failureRate: mockOptions.failureRate ?? 0
    });

    const memoryOperator = new MockMemoryOperator({
      operationDelay: mockOptions.operationDelay ?? 5,
      shouldFail: mockOptions.shouldFail ?? false
    });

    return new MessageBroker(messageProcessor, toolExecutor, memoryOperator);
  }

  /**
   * 创建自定义配置的 MessageBroker
   */
  async createCustomMessageBroker(
    messageProcessor: MessageProcessor,
    toolExecutor: ToolExecutor,
    memoryOperator: MemoryOperator
  ): Promise<MessageBroker> {
    return new MessageBroker(messageProcessor, toolExecutor, memoryOperator);
  }
}

// 便捷的工厂函数
export async function createMessageBroker(config: MessageBrokerConfig): Promise<MessageBroker> {
  const factory = MessageBrokerFactory.getInstance();
  return factory.createMessageBroker(config);
}

// 预设配置
export const MessageBrokerPresets = {
  production: (): MessageBrokerConfig => ({
    mode: 'production'
  }),

  development: (mockOptions?: MessageBrokerConfig['mockOptions']): MessageBrokerConfig => ({
    mode: 'development',
    mockOptions
  }),

  test: (mockOptions?: MessageBrokerConfig['mockOptions']): MessageBrokerConfig => ({
    mode: 'test',
    mockOptions
  }),

  fastTest: (): MessageBrokerConfig => ({
    mode: 'test',
    mockOptions: {
      responseDelay: 1,
      chunkDelay: 1,
      executionDelay: 1,
      operationDelay: 1
    }
  })
};
